<template>
  <BasicModal :footer="null" v-bind="$attrs" @register="registerModal" title="换绑手机" width="500px">
    <div>
      <a-steps :current="current">
        <a-step v-for="item in steps" :key="item.title" :title="item.title" />
      </a-steps>
      <div class="steps-content" v-if="current==0">
        <a-spin :spinning="confirmLoading">
          <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-row>
              <a-col :span="24">
                <a-form-item label="原手机号">
                  <a-input v-model:value="formData.oldPhone" placeholder="请输入原手机号" disabled></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="24">
                <a-form-item label="验证码">
                  <CountdownInput class="fix-auto-fill" v-model:value="formData.oldSms" placeholder="请输入手机验证码" :sendCodeApi="sendCodeApi1" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-spin>
      </div>
      <div class="steps-content" v-if="current==1">
        <a-spin :spinning="confirmLoading">
          <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-row>
              <a-col :span="24" style="margin-bottom: 30px;">
                <span style="font-size: 20px;margin-left: 20px;">
                    <Icon icon="ant-design:exclamation-circle-outlined" size="22"/>
                    <span>更换手机号后原手机号不可登录</span>
                  </span>
              </a-col>
              <a-col :span="24">
                <a-form-item label="新手机号">
                  <a-input-number v-model:value="formData.newPhone" placeholder="请输入新绑定手机号" style="width: 100%;"></a-input-number>
                </a-form-item>
              </a-col>
              <a-col :span="24">
                <a-form-item label="验证码">
                  <CountdownInput class="fix-auto-fill" v-model:value="formData.newSms" placeholder="请输入手机验证码" :sendCodeApi="sendCodeApi2" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-spin>
      </div>
      <div class="steps-action">
        <a-button v-if="current < steps.length - 1" type="primary" @click="next">下一步</a-button>
        <a-button v-if="current == steps.length - 1" type="primary" @click="handleSubmit">完成</a-button>
        <a-button v-if="current > 0" style="margin-left: 8px" @click="prev">上一步</a-button>
      </div>
    </div>
  </BasicModal>
</template>
<script lang="ts" setup>
import { defineExpose, reactive, ref } from "vue";
import { BasicModal, useModalInner } from "/@/components/Modal";
import { useForm } from "/@/components/Form/index";
import { useMessage } from "/@/hooks/web/useMessage";
import { CountdownInput } from "/@/components/CountDown";
import { checkPhoneCode, editPhone, getCaptcha } from "/@/api/sys/user";
import { SmsEnum } from "/@/views/sys/login/useLogin";
import { useUserStoreWithOut } from "/@/store/modules/user";
import { setAuthCache } from "/@/utils/auth";
import { TENANT_ID, TOKEN_KEY } from "/@/enums/cacheEnum";
import { useRouter } from 'vue-router'
const router = useRouter()
import { PageEnum } from "/@/enums/pageEnum";

// 声明Emits
  const emit = defineEmits(['register']);
  const $message = useMessage();
  const formRef = ref();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  const current = ref<number>(0);
  const prev = () => {
    current.value--;
  };
  const steps = reactive([
    {
      title: '验证原手机号',
      content: '',
    },
    {
      title: '绑定新手机号',
      content: '',
    },
  ]);
  const formData = reactive({
    oldPhone: '',
    oldSms: '',
    newPhone: '',
    newSms: '',
  });

  //表单配置
  const [registerForm, { resetFields, validate, clearValidate }] = useForm();
  //表单赋值
  const [registerModal, { setModalProps, closeModal }] = useModalInner();


  //倒计时执行前的函数1
  function sendCodeApi1() {
    if (!formData.oldPhone) {
      $message.createMessage.warning('原手机号码不存在!');
      return;
    }
    return getCaptcha({ mobile: formData.oldPhone, smsmode: SmsEnum.FORGET_PASSWORD,userType: 2,remarks: '换绑手机号' });
  }
  //倒计时执行前的函数2
  function sendCodeApi2() {
    if (!formData.newPhone) {
      $message.createMessage.warning('请输入新绑定的手机号');
      return;
    }else {
      let reg = /^1[3456789]\d{9}$/;
      if (!reg.test(formData.newPhone)) {
        $message.createMessage.warning('手机号码格式错误!');
        return;
      }
      if(formData.newPhone==formData.oldPhone){
        $message.createMessage.warning('新绑定手机号不能与原手机号相同!');
        return;
      }
    }
    return getCaptcha({ mobile: formData.newPhone, smsmode: SmsEnum.REGISTER,userType: 2,remarks: '换绑手机号' });
  }

  async function next(){
    if (!formData.oldPhone) {
      $message.createMessage.warning('原手机号码不存在!');
      return;
    }
    if (!formData.oldSms) {
      $message.createMessage.warning('请输入手机验证码!');
      return;
    }
    confirmLoading.value = true;
    checkPhoneCode({ mobile: formData.oldPhone, captcha: formData.oldSms }).then((res) => {
      if (res.success) {
        current.value++;
      }else {
        $message.createMessage.warning(res.message);
      }
      confirmLoading.value = false;
    });
  }

  //表单提交事件
  async function handleSubmit() {
    if (!formData.newPhone) {
      $message.createMessage.warning('请输入新绑定的手机号码!');
      return;
    }else {
      let reg = /^1[3456789]\d{9}$/;
      if (!reg.test(formData.newPhone)) {
        $message.createMessage.warning('手机号码格式错误!');
        return;
      }
      if(formData.newPhone==formData.oldPhone){
        $message.createMessage.warning('新绑定手机号不能与原手机号相同!');
        return;
      }
    }
    if (!formData.newSms) {
      $message.createMessage.warning('请输入手机验证码!');
      return;
    }
    //提交
    confirmLoading.value = true;
    editPhone({ oldMobile: formData.oldPhone,mobile: formData.newPhone, captcha: formData.newSms, userType: 2}).then((res) => {
      if (res.success) {
        $message.createMessage.success(res.message);
        confirmLoading.value = false;
        //关闭弹窗
        closeModal();
        //更换成功之后跳转到登录界面
        const userStore = useUserStoreWithOut();
        userStore.setToken('');
        setAuthCache(TOKEN_KEY, null);
        setAuthCache(TENANT_ID, null);
        router.push({ path: PageEnum.BASE_LOGIN})
      }else {
        confirmLoading.value = false;
        $message.createMessage.warning(res.message);
      }
    });
  }

  async function show(name) {
    if (!name) {
      $message.createMessage.warning('当前系统无登录用户!');
      return;
    } else {
      formData.oldPhone = name;
      await setModalProps({ visible: true });
    }
  }

  defineExpose({
    show,
  });
</script>
<style scoped>
.steps-content {
  margin-top: 16px;
  border: 1px dashed #e9e9e9;
  border-radius: 6px;
  background-color: #fafafa;
  min-height: 200px;
  text-align: center;
  padding-top: 30px;
}

.steps-action {
  margin-top: 24px;
  float: right;
}

[data-theme='dark'] .steps-content {
  background-color: #2f2f2f;
  border: 1px dashed #404040;
}
</style>
